package com.topteam.frame.entity;

import java.sql.SQLException;
import java.util.List;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.ModelBean;
import com.jfinal.plugin.activerecord.Page;
import com.topteam.utility.CommUtil;
import com.topteam.utility.StringUtil;

@ModelBean("FrameUser")
public class FrameUser extends Model<FrameUser>{
	private static final long serialVersionUID = -2283532856554586231L;
	public static final FrameUser dao = new FrameUser();
	
	/**
	 * 通过用户名查询用户
	 * @param username
	 * @return
	 */
	public FrameUser getUserByUserName(String username){
		return this.findFirst("select * from FrameUser t where t.username=?", username);
	}
	
	public List<FrameUser> getAllUsers(){
		return this.find("select t.* from FrameUser t");
	}
	
	public String encodePassword(String password){
		return CommUtil.md5(password);
	}
	
	public Page<FrameUser> getUserPage(int page, int size){
		return paginate(page, size, "select t.*", "from FrameUser t");
	}
	
	public Page<FrameUser> getUsersByDeptCode(String deptcode,int page, int size){
		return paginate(page, size, "select t.*", "from FrameUser t where t.deptcode like '"+deptcode+"%' order by  t.username ASC");
	}
	
	
	//查询
	public Page<FrameUser> getUserPageBySearch(String username,String displayname,int page, int size){
		String where = " 1=1 ";
		if(StringUtil.isNotNull(username)){
			where += " and t.username like '%"+username+"%'";
		}
		if(StringUtil.isNotNull(displayname)){
			where += " and t.displayname like '%"+displayname+"%'";
		}
		
		where += " order by t.order desc";
		return paginate(page, size, "select t.*", "from FrameUser t where "+ where);
	}
	
	public Page<FrameUser> getUsersBySearchWithDept(String deptcode ,String username,String displayname,int page,int size){
		String where="";
		if(StringUtil.isNotNull(username)){
			where += " and t.username like '%"+username+"%'";
		}
		if(StringUtil.isNotNull(displayname)){
			where += " and t.displayname like '%"+displayname+"%'";
		}
		return paginate(page, size, "select u.*", "from FrameUser u, UserDeptRelation t, FrameDept d where u.id=t.userid and t.deptid=d.id and d.deptcode like '"+deptcode+"%' "+where+" order by  u.order desc");
	}
	
	
	public void deleteIds(String ids) {
		String[] id = ids.split(";");
		for (int i = 0; i < id.length; i++) {
			deleteById(id[i]);
		}
	}
	
	// 重置密码
	public void resetPass(String ids) throws SQLException {
		
		String[] id = ids.split(";");
		
		for (int i = 0; i < id.length; i++) {
			FrameUser u =findById(id[i]);
			u.set("password", CommUtil.md5("11111"));
			u.update();
		}
	}
}
